from django.shortcuts import render
from django.views import View
import json, base64, pickle
from django import http
from django_redis import get_redis_connection

from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE

from meiduo_mall.utils.views import LoginRequiredJSONMixin
# Create your views here.



class CartsSimpleView(View):
    """首页右上角购物车(局部交互展示)"""
    def get(self,request):
        # 判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 用户已登陆,查询展示redis购物车
            redis_conn = get_redis_connection('carts')
            # 查询哈希hash数据{b'3': b'1'}
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 查询set集合数据{b'3'}
            redis_selected = redis_conn.smembers('selected_%s' % user.id)

            # 将redis_cart 和 redis_selected 进行数据结构合并,结构与未登陆购物车数据结构一致
            """
            哈希hash数据{b'3': b'1'}
            查询set集合数据{b'3'}
            {
                "sku_id1":{
                    "count":"1",
                    "selected":"True"
                    },
            }


            """
            carts_dict = {}
            for sku_id,count in redis_cart.items():
                carts_dict[int(sku_id)] ={
                    'count':int(count),
                    'selected': sku_id in redis_selected,
                }

        else:
            #用户未登录,查询展示cookie购物车
            cookies_str_carts = request.COOKIES.get('carts')

            if cookies_str_carts:
                #将cookies_str_carts 字符串 转 cookies_carts_bytes类型字符串
                cookies_carts_bytes =  cookies_str_carts.encode()
                #将cookies_carts_bytes字符串 转 cookies_carts_dict_bytes类型字典
                cookies_carts_dict_bytes = base64.b64decode(cookies_carts_bytes)
                #将cookies_carts_dict_bytes类型字典 转 carts_dict字典
                carts_dict = pickle.loads(cookies_carts_dict_bytes)
            else:
                carts_dict = {}

        # 构造交互购物车响应JSON数据格式
        cart_skus = []
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'count':carts_dict.get(sku.id).get('count'),
                'default_image_uer':sku.default_image.url
            })

        # 响应json列表数据
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','catr_skus':cart_skus})



class CartsSelectAllView(View):
    """全选购物车"""
    def put(self,request):

        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登陆
        user = request.user

        if user.is_authenticated:
            # 已登陆用户,操作redis购物车---------------------------------
            redis_conn = get_redis_connection('carts')
            # pl = redis_conn.pipeline()

            # 获取所有记录
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 获取字典中所有的key
            redis_sku_ids = redis_cart.keys()
            # 判断用户是否全选
            if selected:
                #全选
                redis_conn.sadd('selected_%s' % user.id, *redis_sku_ids)
            else:
                #取消全选
                redis_conn.srem('selected_%s' % user.id,*redis_sku_ids)

            # 响应结果
            return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'ok'})


        else:
            #未登录用户,操作cookie购物车---------------------------------
            # 获取cookie中购物车数据,并且判断购物车是否有数据
            cart_str = request.COOKIES.get('carts')

            #构造响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

            if cart_str:
                # 将cart_str字符串 转 cart_str_bytes字符串
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes字符串 转 cart_dict_bytes字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将cart_dict_bytes字典 转 cart_dict字典数据
                cart_dict = pickle.loads(cart_dict_bytes)


                #遍历所有都购物车记录
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected

                # 将cart_dict字典 转为 cart_dict_bytes字典
                cart_dict_bytes = pickle.dumps(cart_dict)
                # 将 cart_dict_bytes字典 转 cart_str_bytes字符串
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                # 将 cart_str_bytes字符串 转 cart_str字符串数据
                cookie_cart_str = cart_str_bytes.decode()

                # 重新将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str)

            # 响应结果
            return response



class CartsView(View):
    """购物车管理"""
    def post(self,request):
        """保存购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id') # 必传参数
        count = json_dict.get('count') # 必传参数
        selected = json_dict.get('selected', True) # 可选

        # 校验参数
        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 校验sku_id是否合法
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('参数sku_id错误')
        # 校验count是否是数字
        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('参数count错误')
        # 校验勾选是否是bool类型
        if selected:
            if not isinstance(selected,bool):
                return http.HttpResponseForbidden('参数selected错误')

        # 判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 如果用户已登陆,操作redis购物车
            redis_conn = get_redis_connection('carts')

            pl = redis_conn.pipeline()

            # 需要以增量计算的形式保存商品数据
            pl.hincrby('carts_%s' % user.id, sku_id, count)
            # 保存商品勾选状态
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            # 执行
            pl.execute()

            # 响应结果
            return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'ok'})

        else:
            # 如果用户未登陆,操作cookie购物车
            # 获取cookie中的购物车数据,并且判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')
            # 如果购物车数据存在
            if cart_str:
                # 将cart_str字符串转为bytes类型字符串
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes字符串转为bytes类型字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将cart_dict_bytes转为字典
                cart_dict = pickle.loads(cart_dict_bytes)

            # 如果购物车数据不存在
            else:
                cart_dict = {}

            # 判断当前要添加的商品在cart_dict中是否存在
            if sku_id in cart_dict:
                #购物车已存在,增量计算
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            # 如果购物车内不存在该同一商品,则直接添加
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
                }

            # 将原始购物车字典进行编码
            # 将cart_dict转bytes类型字典
            cart_dict_bytes = pickle.dumps(cart_dict)
            # 将cart_dict_bytes类型字典 转 bytes类型字符串
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            # 将cart_str_bytes类型字符串 转 字符串
            cookie_cart_str = cart_str_bytes.decode()

            # 将新的购物车数据写入cookie
            response = http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})
            response.set_cookie('carts',cookie_cart_str)


            # 响应结果
            return response

    def get(self,request):
        """查询购物车"""
        #判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 已登陆用户,查询redis购物车
            # 创建链接到redis的对象
            redis_conn = get_redis_connection('carts')

            # 查询hash哈希数据
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)

            # 查询set数据
            redis_selected = redis_conn.smembers('selected_%s' % user.id)

            cart_dict = {}
            # 将 redis_cart 和 redis_selected 进行数据结构的构造,合并数据 数据结构和未登录用户购物车结构一致
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)]= {
                    'count': int(count),
                    'selected': sku_id in redis_selected
                }
        else:
            # 未登陆用户,查询cookie购物车
            # 获取cookie中的购物车数据,并且判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')
            # 如果购物车数据存在
            if cart_str:
                # 将cart_str字符串转为bytes类型字符串
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes字符串转为bytes类型字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将cart_dict_bytes转为字典
                cart_dict = pickle.loads(cart_dict_bytes)
            # 如果购物车数据不存在
            else:
                cart_dict = {}

        # 构造响应数据

        # 获取字典中所有的key(sku_id)
        sku_ids = cart_dict.keys()

        # for sku_id in sku_ids:
        #     sku = SKU.objects.get(id=sku_id)

        # 一次查询所有的skus
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id':sku.id,
                'count':cart_dict.get(sku.id).get('count'),
                'selected':str(cart_dict.get(sku.id).get('selected')), # 将True转'True', 便于json解析
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'price':str(sku.price),
                'amount':str(sku.price * cart_dict.get(sku.id).get('count'))
            })

        context = {
            'cart_skus':cart_skus

        }

        # 渲染购物车页面
        return render(request,'cart.html',context)

    def put(self,request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_conn = get_redis_connection('carts')
            # 由于后端收到的数据是最终结果,所以直接"覆盖原数据写入"
            # redis_conn.hincrby() 增量计算(新值加旧值)
            redis_conn.hset('carts_%s' % user.id, sku_id, count)
            pl = redis_conn.pipeline()

            # 修改勾选状态
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            # 执行
            pl.execute()


            # 创建响应对象数据
            cart_sku = {
                'id': sku_id,
                'count':count,
                'selected':selected,
                'name':sku.name,
                'price':sku.price,
                'amount':sku.price * count,
                'default_image_url':sku.default_image.url
            }

            # 响应结果
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_sku': cart_sku})
        else:
            # 用户未登录，修改cookie购物车
            # 如果用户未登陆,操作cookie购物车
            # 获取cookie中的购物车数据,并且判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')
            # 如果购物车数据存在
            if cart_str:
                # 将cart_str字符串转为bytes类型字符串
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes字符串转为bytes类型字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将cart_dict_bytes转为字典
                cart_dict = pickle.loads(cart_dict_bytes)
            # 如果购物车数据不存在
            else:
                cart_dict = {}

            # 由于后端收到的是最终的结果,所以"覆盖写入"
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 创建响应对象数据
            cart_sku = {
                'id': sku_id,
                'count':count,
                'selected':selected,
                'name':sku.name,
                'price':sku.price,
                'amount':sku.price * count,
                'default_image_url':sku.default_image.url
            }


            # 将原始购物车字典进行编码
            # 将cart_dict转bytes类型字典
            cart_dict_bytes = pickle.dumps(cart_dict)
            # 将cart_dict_bytes类型字典 转 bytes类型字符串
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            # 将cart_str_bytes类型字符串 转 字符串
            cookie_cart_str = cart_str_bytes.decode()

            # 将新的购物车数据写入cookie
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_sku':cart_sku })
            response.set_cookie('carts', cookie_cart_str)

            # 响应结果
            return response

    def delete(self,request):
        """删除购物车商品"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        # 判断用户是否登陆
        user = request.user
        if user is not None and user.is_authenticated:
            # 已登录用户, 删除redis购物车
            redis_conn = get_redis_connection('carts')

            pl = redis_conn.pipeline()
            # 删除hash哈希类型 购物车商品记录
            pl.hdel('carts_%s' % user.id, sku_id)
            # 同步删除set中勾选状态
            pl.srem('selected_%s' % user.id,sku_id)
            # 执行
            pl.execute()
            return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'ok'})
        else:
            # 未登陆用户,删除cookie购物车
            # 获取cookie中的购物车数据,判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str 转成 bytes类型的字符串
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes类型的字符串 转 bytes类型字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将cart_dict_bytes类型字典 转 字典数据
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

            # 构造响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

            # 删除 字典指定key所对应的记录(核心)
            if sku_id in cart_dict:
                del cart_dict[sku_id] # 如果删除的key不存在,会抛异常 所以增加判断

                # 将cart_dict转成 bytes类型字典
                cart_dict_bytes = pickle._dumps(cart_dict)
                # 将cart_dict_bytes类型字典 转 bytes类型字符串
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                # 将cart_str_bytes类型字符串 转 字符串数据
                cookie_cart_str = cart_str_bytes.decode()

                # 写入心的cookie
                response.set_cookie('carts',cookie_cart_str)

            return response


